package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1605. 给定行和列的和求可行矩阵
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/17 13:11
 */
public class RestoreMatrix {


    public static void main(String[] args) {


        RestoreMatrix test = new RestoreMatrix();

//        int[] arr = {5, 7, 10};
//        int[] arr2 = {8, 6, 8};

        int[] arr = {43, 6, 0};
        int[] arr2 = {14, 2, 14, 4, 15};

        int[][] ints = test.restoreMatrix(arr, arr2);
        for (int[] anInt : ints) {
            System.out.println(Arrays.toString(anInt));
        }
    }


    public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
        int r = rowSum.length;
        int c = colSum.length;
        int[][] arr = new int[r][c];
        int[] ints = arr[0];
        long sum = 0;
        for (int i = 0; i < c; i++) {
            ints[i] = colSum[i];
            sum += colSum[i];
        }
        for (int i = 0; i < r; i++) {
            arr[i][0] = rowSum[i];
        }
        sum = rowSum[0] - sum + colSum[0];
        if (sum < 0) {
            arr[0][0] = 0;
            sum *= -1;
            int i = 1;
            int j = 1;
            while (true) {
                int a = arr[i][0];
                int b = arr[0][j];
                if (Math.min(a, b) >= sum) {
                    arr[i][0] -= sum;
                    arr[0][j] -= sum;
                    arr[i][j] += sum;
                    break;
                }
                if (a < b) {
                    sum -= a;
                    arr[i][0] = 0;
                    arr[0][j] -= a;
                    arr[i][j] += a;
                    i++;
                } else {
                    sum -= b;
                    arr[i][0] -= b;
                    arr[0][j] = 0;
                    arr[i][j] += b;
                    j++;
                }
            }
        } else {
            arr[0][0] = (int) sum;
        }
        return arr;
    }

}
